package concurrency;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.Sun
 * @date 2022年09月06日 11:18
 */
public class Philosopher implements Runnable {

    // 左边的筷子
    private final Chopstick left;
    // 右边的筷子
    private final Chopstick right;
    private final int id;
    // 权重因子
    private final int ponderFactor;

    private Random random = new Random(47);

    public Philosopher(Chopstick left, Chopstick right, int id, int ponderFactor) {
        this.left = left;
        this.right = right;
        this.id = id;
        this.ponderFactor = ponderFactor;
    }

    private void pause() throws InterruptedException {
        if (ponderFactor == 0) {
            return;
        }

        TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFactor * 250));
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(this + "  正在思考");
                pause();
                // 哲学家饿了
                System.out.println(this + " 拿走右手边的筷子");
                right.take();
                System.out.println(this + " 拿走左手边的筷子");
                left.take();
                System.out.println(this + " 正在就餐");
                pause();
                right.drop();
                left.drop();
            }
        } catch (InterruptedException e) {
            System.out.println(this + " exiting via interrupt");
        }
    }

    @Override
    public String toString() {
        return "哲学家 " + id;
    }
}
